package com.zzu.view.fragment;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.zzu.R;
import com.zzu.adapter.OneAdapter;
import com.zzu.adapter.RouteAdapter;
import com.zzu.model.bean.PackageDetail;
import com.zzu.model.bean.PackageRoute;
import com.zzu.model.bean.PackageRouteDetail;
import com.zzu.presenter.impl.PackageRoutePresenterImpl;
import com.zzu.view.view.PackageQueryView;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于显示地图
 */
public class MapFragment extends Fragment {

    private static final String TAG = MapFragment.class.getName();

    private MapView mMapView;
    private AMap aMap;


    TextView tvRouteInfo = null;
    TextView tvPackageID = null;//包裹id
    TextView tvPackageInfo = null;
    RecyclerView routeList = null;

    private Context mContext;
    private static final String PACKAGE_ID = "package_id";
    //包裹快递单号,默认快递号为1234567891234
    private String packageId = "1234567891234";

    public MapFragment() {
        // Required empty public constructor
    }

    public static MapFragment newInstance(String packageId) {
        MapFragment fragment = new MapFragment();
        Bundle args = new Bundle();
        args.putString(PACKAGE_ID, packageId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            //获取包裹id
            packageId = getArguments().getString(PACKAGE_ID);
        }
        Log.i(TAG,"获得到的包裹id"+packageId);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map, container, false);

        mMapView = view.findViewById(R.id.map);
        tvRouteInfo = view.findViewById(R.id.tv_route_info);
        tvPackageID = view.findViewById(R.id.tv_package_id);
        tvPackageInfo = view.findViewById(R.id.tv_package_info);
        routeList = view.findViewById(R.id.route_list);

        mMapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        //设置缩放级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
        //取消比例尺按钮
        aMap.getUiSettings().setZoomControlsEnabled(false);
        initData();
        return view;
    }

    //从数据库中查询包裹的路线数据
    private void initData() {

        //设置包裹id
        tvPackageID.setText(packageId);

        new PackageRoutePresenterImpl(mContext, new PackageQueryView<List<PackageRouteDetail>>() {

            @Override
            public void getDates(List<PackageRouteDetail> datas) {
                Log.i(TAG,"获得到的数据："+datas);
                if(datas != null || datas.size() > 0){
                    Log.i(TAG,"获得到的数据："+datas);
                    setDataForView(datas);
                    //存在数据，根据x和y将数据进行分类
                }else{
                    //当前包裹未揽收
                    tvPackageInfo.setText("(暂无包裹信息)");
                }
            }

            @Override
            public void getNoDate() {

            }

        }).getPackageRouteDetailByPackageId(packageId);

    }


    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
        Log.i(TAG,"调用onresume方法");
        initData();

    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    private void setDataForView(List<PackageRouteDetail> list) {
        PackageRouteDetail tmp;
        Marker now;
        String stname = null;
        String endname = null;
        boolean flg = true;
        boolean rev = false;
        float x1 = 360, x2 = -360;
        float y1 = 360, y2 = -360;
        //存在数据，根据x和y将数据进行分类
        List<PackageRouteDetail> route = new ArrayList<>();
        List<LatLng> latLngs = new ArrayList<LatLng>();

        for(int i=0; i<list.size(); ++i){
            if(list.get(i).getX() == null || Math.abs(list.get(i).getX())<1e-5) {
                tmp = list.remove(i);
                if (flg) {//起点
                    flg = false;
                    stname = tmp.getTransNode();
                } else if (tmp.getStatus() != 5) {//中间转运站
                    if(i-1>=0){
                        now = aMap.addMarker(make(R.mipmap.trans, new LatLng(list.get(i - 1).getX(), list.get(i - 1).getY())));
                        now.setTitle(tmp.getStringStatue());
                        now.setSnippet(tmp.getTransNode());
                    }
                } else {//收货点
                    rev = true;
                    endname = tmp.getTransNode();
                }
                //列表项
                route.add(tmp);
                --i;
            }
        }

        if(route.size() == 0){
            tvPackageInfo.setText("(暂无包裹信息)");
        }

        //进行适配器的设置
        RouteAdapter adapter = new RouteAdapter(mContext, route);
        routeList.setAdapter(adapter);
        //设置布局管理器
        routeList.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));

        if(list.size() == 0){
            //没有路线信息
            tvRouteInfo.setText("暂无路线信息");
            return;
        }
        //起点
        Marker st = aMap.addMarker(make(R.mipmap.exstart, new LatLng(list.get(0).getX(),list.get(0).getY())));
        st.setTitle("已发件");
        st.setSnippet(stname);

        //可视区域
        int end = list.size();
        for(int i=0; i < end; ++i){
            x1 = Math.min(x1, list.get(i).getX());
            x2 = Math.max(x2, list.get(i).getX());
            y1 = Math.min(y1, list.get(i).getY());
            y2 = Math.max(y2, list.get(i).getY());
            latLngs.add(new LatLng(list.get(i).getX(), list.get(i).getY()));
        }
        //将地图移动到定位点
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(list.get(end-1).getX(),list.get(end-1).getY())));
        if(rev){
            //已收件
            now = aMap.addMarker(make(R.mipmap.exend, new LatLng(list.get(end-1).getX(),list.get(end-1).getY())));
            now.showInfoWindow();
            now.setTitle("已签收");
            now.setSnippet(endname);
        }else {
            //运输中
            now = aMap.addMarker(make(R.mipmap.truck, new LatLng(list.get(end-1).getX(),list.get(end-1).getY())));
            now.showInfoWindow();
            now.setTitle("运输中");
        }

        Polyline polyline = aMap.addPolyline(new PolylineOptions().
                addAll(latLngs).width(10).color(Color.argb(255, 255, 0, 0)));

        //地图可视区域上移
        LatLngBounds.Builder b = LatLngBounds.builder();

        b.include(new LatLng(x1 - 0.005, y1));
        b.include(new LatLng(x2, y2));
        aMap.animateCamera(CameraUpdateFactory
                .newLatLngBounds(b.build(), 40));

    }

//    private void setDataForView(List<PackageRouteDetail> route, List<PackageRouteDetail> list) {
//        Log.i(TAG,"列表数据"+route+",路线数据"+list);
//        //进行适配器的设置
//        RouteAdapter adapter = new RouteAdapter(mContext, route);
//        routeList.setAdapter(adapter);
//        //设置布局管理器
//        routeList.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
//        //画线
//        if(list.size() > 0){
//            List<LatLng> latLngs = new ArrayList<LatLng>();
//            //起点
//            aMap.addMarker(make(R.mipmap.exstart, new LatLng(list.get(0).getX(),list.get(0).getY())));
//
//            int end = list.size();
//            for(int i=0; i < end; ++i){
//                Log.i(TAG, "notifyDataSetChanged: "+list.get(i).getX()+", "+list.get(i).getY());
//                latLngs.add(new LatLng(list.get(i).getX(), list.get(i).getY()));
//            }
//
//            //当前位置
//            aMap.addMarker(make(R.mipmap.exend, new LatLng(list.get(end-1).getX(),list.get(end-1).getY())));
//
//            Polyline polyline = aMap.addPolyline(new PolylineOptions().
//                    addAll(latLngs).width(10).color(Color.argb(255, 0, 191, 255)));
//        }
//
//
//    }

    private MarkerOptions make(int id, LatLng latLng){//自定义marker

        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);

        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), id)));

        return markerOption;
    }

}